<?php
include_once 'paomeBase.class.php';

/**
 * 首页相关
 */
class homeModel extends paomeBaseModel
{

    public function __construct(& $base)
    {
        parent::__construct($base);

        $this->table = 'r_pm_contest';
    }

    /**
    * 创建俱乐部消耗正能量
    */
    public function expendEnergy($uid) {
        $userInfo = $this->base->load('client')->getUserInfo($uid);
        $result = true;
        if($userInfo['total_energy'] < 100){
            $result = false;
        }else{
            //正能量表更新
            $this->base->load('client')->userEnergyChange($uid,'paomeCreateClub');
        }        
        return $result;
    }

    /**
    * 赛季内当前轮次阶段对应的时间
    */
    public function getTimeRang() {
        //获取当前赛季
        $season = $this->base->load("paome/paomeHall")->getCurrentSeason();
        $timeRang = array();
        if($season){
            //获取当前所处阶段
            $phase = $this->base->load("paome/paomeHall")->getPhaseByTime(time(), time());
            
            //阶段与轮次对应字典
            $phaseDict = array(
                1 => array(1, 5, 6, 10, 11),
                2 => array(12, 15, 16, 20, 21),
                3 => array(/*22,*/ 25, 26, 30, 31),  //第一期没有第三轮，特殊处理
                4 => array(22/*32*/, 105, 106),
            );
            //根据当前阶段取当前轮次
            $currentRound = 0;
            $currentPhase = 0;
            if(!empty($phase)){
                foreach ($phaseDict as $k => $v) {
                    if(in_array($phase['type'], $v)){
                        $currentRound = $k;
                    }
                }
                //每一轮的状态字典
                $roundStatus = array(
                    1 => array(1, 12, 22, 32),   //即将开始
                    2 => array(5, 15, 25),   //预选赛
                    3 => array(10, 20, 30),   //冠军赛
                    4 => array(6, 16, 26),   //预选赛空档期
                    5 => array(11, 21, 31),   //冠军赛空档期
                    6 => array(106),   //争霸赛空档期
                    7 => array(120),   //赛季结束
                    8 => array(105),   //争霸赛进行中
                );
                foreach ($roundStatus as $x => $y) {
                    if(in_array($phase['type'], $y)){
                        $currentPhase = $x;
                    }
                }
                $timeRang['currentRound'] = $currentRound;
                $timeRang['currentPhase'] = $currentPhase;
                //获取当前赛季所有轮次
                $rounds = $this->base->load("paome/paomeHall")->getPhaseBySeason($season['id']);
                if($rounds){
                    foreach ($rounds as &$v) {
                        if($currentRound == 1){
                            if($v['type'] == 5){
                                $timeRang['start_time'] = $v['start_time'];
                                $timeRang['qualifying_start'] = $v['start_time'];
                                $timeRang['qualifying_end'] = $v['end_time'];
                            }
                            if($v['type'] == 10){
                                $timeRang['championship_start'] = $v['start_time'];
                                $timeRang['championship_end'] = $v['end_time'];
                                $timeRang['end_time'] = $v['end_time'];
                            }
                        }
                        if($currentRound == 2){
                            if($v['type'] == 15){
                                $timeRang['start_time'] = $v['start_time'];
                                $timeRang['qualifying_start'] = $v['start_time'];
                                $timeRang['qualifying_end'] = $v['end_time'];
                            }
                            if($v['type'] == 20){
                                $timeRang['championship_start'] = $v['start_time'];
                                $timeRang['championship_end'] = $v['end_time'];
                                $timeRang['end_time'] = $v['end_time'];
                            }
                        }
                        if($currentRound == 3){
                            if($v['type'] == 25){
                                $timeRang['start_time'] = $v['start_time'];
                                $timeRang['qualifying_start'] = $v['start_time'];
                                $timeRang['qualifying_end'] = $v['end_time'];
                            }
                            if($v['type'] == 30){
                                $timeRang['championship_start'] = $v['start_time'];
                                $timeRang['championship_end'] = $v['end_time'];
                                $timeRang['end_time'] = $v['end_time'];
                            }
                        }
                        if($currentRound == 4){
                            if($v['type'] == 105){
                                $timeRang['start_time'] = $v['start_time'];
                                $timeRang['end_time'] = $v['end_time'];
                                $timeRang['qualifying_start'] = $v['start_time'];
                                $timeRang['qualifying_end'] = $v['end_time'];
                                $timeRang['championship_start'] = $v['start_time'];
                                $timeRang['championship_end'] = $v['end_time'];
                            }
                        }
                    }
                }
            }
        }   
        return $timeRang;
    }

    /*
     * 首页--明星成员
     */
    public function getHomeStarUser($order, $sort = 'DESC'){
        //获取当前赛季
        $season = $this->base->load("paome/paomeHall")->getSeasonByTime(time(), time());
        $starUser = array();
        if($season){
            $seasonId = $season['id'];
            $round = $this->base->load("paome/paomeHall")->getCurrentRound();
            if(!empty($round)){
                $sql = "SELECT * FROM r_pm_users_rounds r WHERE r.type = {$round} AND contest_id = {$seasonId} AND {$order} > 0 ORDER BY {$order} {$sort}";
                $starUser = $this->paomeDb->getRow($sql);
            }
        }
        return $starUser;
    }

    /*
     * 获取招募期内创建的俱乐部信息
     */
    public function getClubInRecruit($start){
        //获取当前赛季
        $season = $this->base->load("paome/paomeHall")->getSeasonByTime(time(), time());
        $club = array();
        if($season){
            $round = $this->paomeDb->getRow("select * from r_pm_rounds where type = 1 and contest_id = {$season['id']}");
            if($round){
               $club = $this->paomeDb->getRow("select * from r_pm_club where status = 0 and (create_time between {$round['start_time']} and {$round['end_time']}) limit {$start}, 1"); 
            }
        }
        return $club;
    }

    /*
     * 获取招募期内创建的俱乐部数量
     */
    public function getClubInRecruitNum(){
        //获取当前赛季
        $season = $this->base->load("paome/paomeHall")->getSeasonByTime(time(), time());
        $count = 0;
        if($season){
            $round = $this->paomeDb->getRow("select * from r_pm_rounds where type = 1 and contest_id = {$season['id']}");
            if($round){
               $count = $this->paomeDb->getOne("select count(1) from r_pm_club where status = 0 and (create_time between {$round['start_time']} and {$round['end_time']})"); 
            }
        }
        return $count;
    }

    /*
     * 获取成员数未满上限的俱乐部(人数最多)
     */
    public function HomeClubRecomment($uid){
        $season = $this->base->load("paome/paomeHall")->getSeasonByTime(time(), time());
        $data = array();
        if($season){
            $seasonId = $season['id'];
            $diffCount = 5;

            $auditSql = "SELECT c.*, @isJoin := 1 as isJoin FROM r_pm_club c RIGHT JOIN r_pm_club_users s ON c.id = s.club_id WHERE c. STATUS = 0 AND s. STATUS = - 1 AND s.uid = {$uid} ORDER BY c.user_num DESC LIMIT 5";
            $auditArr = $this->paomeDb->getAll($auditSql);
            !empty($auditArr) && $diffCount = 5 - count($auditArr);

            $sql = "SELECT c.*, @isJoin := 0 as isJoin FROM r_pm_club c RIGHT JOIN r_pm_club_status s ON c.id = s.club_id WHERE c.user_num < 30 AND c. STATUS = 0 AND s.contest_id = $seasonId AND s.type IN (1, 10, 20, 100) AND s. STATUS IN (0, 15) AND c.id not in (SELECT club_id FROM r_pm_club_users where uid = {$uid} and status = -1) ORDER BY c.user_num DESC limit {$diffCount}";

            if(in_array($season['status'], array(22, 32))){
                $sql = "SELECT c.*, @isJoin := 0 as isJoin FROM r_pm_club c RIGHT JOIN r_pm_champions_member s ON c.id = s.club_id WHERE c.user_num < 30 AND s.contest_id = $seasonId  AND c.id not in (SELECT club_id FROM r_pm_club_users where uid = {$uid} and status = -1) ORDER BY c.user_num DESC limit {$diffCount}";
            }
            $notJoin = $this->paomeDb->getAll($sql);
            $data = array_merge($auditArr, $notJoin);
        }
        
        return $data;
    }

    /*
     * 查看成员加入俱乐部状态(待审核还是已加入)
     */
    public function userClubStatus($uid){
        $sql = "select u.* from r_pm_club_users u left join r_pm_club c on u.club_id = c.id  where u.status != -5 and u.uid = {$uid} and c.status = 0 order by u.create_time";
        $data = $this->paomeDb->getRow($sql);
        return $data;
    }

    /*
     * 查看俱乐部是否具有争霸赛资格
     */
    public function clubChampions($seasonId, $clubId){
        $sql = "select * from r_pm_champions_member where contest_id = {$seasonId} and club_id = {$clubId}";
        $data = $this->paomeDb->getRow($sql);
        return $data;
    }

    /*
     * 获取俱乐部
     */
    public function latestClub($where = null, $order = null){
        $sql = "select * from r_pm_club";
        !empty($where) && $sql .= " where {$where}";
        !empty($order) && $sql .= " order by {$order}";
        $data = $this->paomeDb->getRow($sql);
        return $data;
    }

    /*
     * 根据阶段获取公告
     */
    public function getAffiche($seasonId, $rounds, $content, $type, $clubId = null){
        $sql = "select * from r_pm_affiche where contest_id = {$seasonId} and rounds = {$rounds} and content = \"{$content}\" and type = {$type} and is_show = 1";
        !empty($clubId) && $sql .= " and club_id = {$clubId}";
        $data = $this->paomeDb->getRow($sql);
        return $data;
    }

    /*
     * 首页--根据战队获取跑量最大的用户信息
     */
    public function getMaxUserInClub($clubId, $paomeId, $roundId){
        $sql = "SELECT * FROM r_pm_users_rounds r WHERE r.type = {$roundId} AND contest_id = {$paomeId} and uid in (select uid from r_pm_club_users where status = 0 and club_id = {$clubId}) ORDER BY mileage DESC";
        $maxUserInfo = $this->paomeDb->getRow($sql);
        $maxUser = array();
        if($maxUserInfo){
            $maxUser['uid'] = $maxUserInfo['uid'];
            $maxUser['mileage'] = $maxUserInfo['mileage'];
            $maxUser['userRank'] = '';
            $maxUser['userNum'] = '';
            //全员排名
            $rankUserKeyMile = 'rankUser-mileage-'.$paomeId.'-'.$roundId;
            if($this->redis->zCard($rankUserKeyMile)) {
                $maxUser['userRank'] = $this->redis->zRevRank($rankUserKeyMile,$maxUser['uid'])+1;
                $maxUser['userNum'] = $this->redis->zSize($rankUserKeyMile);
            }
            $maxUser['nickname'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $maxUser['uid'], 'nickname');
            $maxUser['header'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $maxUser['uid'], 'header');
        }
        empty($maxUser) && $maxUser = array('uid'=>'','mileage'=>'','userRank'=>'','userNum'=>'','nickname'=>'','header'=>'');
        return $maxUser;
    }

    /*
     * 首页--查询战队的累计积分(截止昨天)
     */
    public function getClubSumScore($clubId){
        $season = $this->base->load('paome/paomeHall')->getCurrentSeason();
        $clubSumScore = array();
        if(!empty($season)){
            $paomeId = $season['id'];
            $roundId = $this->base->load('paome/paomeHall')->getCurrentRound();
            $sql = "SELECT * FROM r_pm_score WHERE type = {$roundId} AND contest_id = {$paomeId} and club_id = {$clubId}";
            $clubSumScore = $this->paomeDb->getRow($sql);
        }
        return $clubSumScore;
    }
}